Skip to content

Async control-flow modeling: spawn/join classification, coroutine-state guard recognition - #2

Merged
kevindadi merged 11 commits into
mainfrom
async
Aug 26, 2026
Merged

kevindadi merged 11 commits into
mainfrom
async

Conversation

@kevindadi

@kevindadi kevindadi commented Aug 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

Models Rust async/tokio control flow in the MIR→Petri-net pipeline: task spawn, JoinHandle.await, and lock guards held across .await suspend points. Adds an async-deadlock bench and documents the one remaining PTA gap.

Changes

  1. Async spawn/join classification (config.rs, structure.rs, callgraph.rs)

    • New async_spawn / async_join config regexes (tokio::spawn, etc.).
    • New ThreadControlKind::AsyncSpawn / AsyncJoin.
    • classify_async_join_by_ty: .await on a JoinHandle lowers to core::future blanket impls (into_future / Pin<&mut _>::poll) whose def-paths never mention JoinHandle, so the join site is recognized by inspecting the awaited future's type.
  2. Coroutine future resolution (closure.rs, thread_control.rs)

    • resolve_closure_def_id now resolves TyKind::Coroutine / CoroutineClosure, so tokio::spawn(task(...))'s future resolves to its (start, end) places and handle_join can link the spawned task's end into the .await join transition.
  3. Coroutine-state guard recognition (blocking.rs, pointsto.rs, calls.rs, drop_unsafe.rs)

    • LockGuardId gains a field so a guard stored in coroutine state ((*_state as variant#N).k) is keyed by its field.
    • BlockingCollector::register_projected_guard collects guards whose lock() destination is a projection and records the resolved receiver; handle_lock_call / handle_drop look up guards field-sensitively.
  4. PTA groundwork (builder.rs)

    • Rvalue::Aggregate handles AggregateKind::Coroutine / CoroutineClosure like closures (records construction site + env heap). Foundation for coroutine-layout modeling.
  5. Bench + docs

    • bench/deadlock/async-deadlock/ — two tokio tasks, AB–BA lock order across .await.
    • docs/async-modeling.md — design, the type-check rationale, and the open PTA gap.

Known remaining gap

Cross-instance Arc<Mutex> aliasing through coroutine state is still unsound: coroutines read upvars via _1.0 → State → Downcast(variant#N) → field, which the closure-style _1.field_i env binding doesn't match, so the four guards in the bench split into four lock resources instead of two. Fix requires tcx.coroutine_layout modeling (documented in docs/async-modeling.md).


Note

Medium Risk
Touches core PTA env binding, lock-guard identity, and Petri-net control flow for coroutines. Heuristic string checks (Poll::Pending, JoinHandle in types) can mis-classify unrelated futures or inflate/miss deadlocks.

Overview
Enables deadlock detection on async/tokio tasks: tokio::spawn and JoinHandle.await are wired like thread spawn/join, and mutex guards stored in coroutine state across .await are tracked as real lock resources.

Spawn/join. New AsyncSpawn/AsyncJoin kinds plus config regexes. Because .await lowers to core::future blanket poll/into_future, join is recognized by type (JoinHandle in the awaited ty) and only on ::poll so the task end token is not consumed twice.

PTA + guards. Coroutine aggregates reuse closure upvar heaps. Env binding for coroutines points _1.0 (Pin<&mut State>) at that heap so Arc<Mutex> captures alias across tasks. LockGuardId is field-sensitive; projected lock() destinations in state variants are registered with their receiver.

Control flow. Poll::Pending returns resume to the continuation instead of completing the task (which leaked held locks). Coroutine bb0 dispatch only takes the entry discriminant so resume states are not explored from the initial poll.

The new bench/deadlock/async-deadlock (AB–BA across sleep().await) is documented as reporting exactly one deadlock.

Reviewed by Cursor Bugbot for commit d2d0747. Bugbot is set up for automated code reviews on this repo. Configure here.

- Created a new Cargo.toml for the async-deadlock benchmark, specifying dependencies on `tokio` and `parking_lot`.
- Implemented the main logic in src/main.rs, featuring two asynchronous tasks that demonstrate deadlock potential using mutexes.
- Utilized Arc and Mutex from the parking_lot crate to manage shared state across tasks.
- Added `async_spawn` and `async_join` fields to `PnConfig` for better async control.
- Updated `ThreadControlKind` enum to include `AsyncSpawn` and `AsyncJoin`.
- Enhanced thread control classification to recognize async spawn and join patterns.
- Modified `BodyToPetriNet` to handle async thread control, improving the analysis of async tasks.
- Renamed the original async task to `task1` and created a new async task `task2` to demonstrate different locking patterns.
- Updated the main function to spawn the new task names, maintaining the benchmark's focus on async deadlock scenarios.
- Removed the pn.toml.example configuration file as it is no longer needed.
- Updated LockGuardId to include an optional field index for guards stored in coroutine/struct states.
- Refactored BlockingCollector to utilize the new lockguard_id_for_dest method, improving the handling of lock-call destinations and ensuring accurate tracking of guard projections.
- Enhanced alias ID generation to incorporate the field index from LockGuardId, improving alias analysis accuracy.
- Reorganized imports for better structure and readability.
- Enhanced the `proj_kinds` function to improve formatting and clarity.
- Updated the handling of closure and coroutine aggregates in `process_closure_aggregate`, ensuring accurate upvar type collection.
- Improved the formatting of constraint additions for better readability.
- Streamlined the handling of environment paths for closures and coroutines, enhancing maintainability.
@kevindadi

Copy link
Copy Markdown
Owner Author

Screenshot

Reduced Petri net for bench/deadlock/async-deadlock (the four Mutex_0..3 places are the current aliasing gap — see below):

async-deadlock petri net

Reproduction

Bench source (bench/deadlock/async-deadlock/src/main.rs) — two tokio tasks, AB–BA lock order, guards held across .await:

async fn task1(a: Arc<Mutex<i32>>, b: Arc<Mutex<i32>>) {
    let _ga = a.lock();
    tokio::time::sleep(Duration::from_millis(10)).await;
    let _gb = b.lock();
}
async fn task2(a: Arc<Mutex<i32>>, b: Arc<Mutex<i32>>) {
    let _ga = a.lock();
    tokio::time::sleep(Duration::from_millis(10)).await;
    let _gb = b.lock();
}
#[tokio::main]
async fn main() {
    let l1 = Arc::new(Mutex::new(0));
    let l2 = Arc::new(Mutex::new(0));
    let h1 = tokio::spawn(task1(l1.clone(), l2.clone()));
    let h2 = tokio::spawn(task2(l2.clone(), l1.clone()));
    let _ = h1.await;
    let _ = h2.await;
}

Run:

./detect.sh bench/deadlock/async-deadlock/ -m deadlock --pn-analysis-dir=tmp/async-verify --viz-petrinet --viz-stategraph

What fires (classification)

JoinHandle.await is recognized by type, not def-path (the callee is a core::future blanket impl):

[async] AsyncSpawn: tokio::task::spawn::spawn
[async] AsyncJoin: core::future::into_future::IntoFuture::into_future (ty=tokio::task::JoinHandle<()>)
[async] AsyncJoin: core::future::future::Future::poll (ty=std::pin::Pin<&'erased mut tokio::task::JoinHandle<()>>)

Lock grouping (the open gap)

Both guards per task are now collected (incl. the one held across .await), but the four receivers split into four resources instead of two real locks (task1.a/task2.b are both l1; task1.b/task2.a are both l2):

[lockgroup-detail] group0 ["{closure#0}::task1::__15(rx19fSome(1))"] = ParkingLotMutex
[lockgroup-detail] group1 ["{closure#0}::task1::__19(rx19fSome(0))"] = ParkingLotMutex
[lockgroup-detail] group2 ["{closure#0}::task2::__19(rx19fSome(0))"] = ParkingLotMutex
[lockgroup-detail] group3 ["{closure#0}::task2::__15(rx19fSome(1))"] = ParkingLotMutex

Every cross-instance alias query returns Unlikely; the coroutine reads upvars via _1.0 → State → Downcast(variant#N) → field, which the closure-style _1.field_i env binding doesn't populate. Fix = tcx.coroutine_layout modeling (see docs/async-modeling.md).

Result

Result   : BUG FOUND   (mode deadlock)
Bug count: 11   states=351, edges=767, reachable=351


if let ty::FnDef(def_id, substs) = *func_ty.kind() {
let fn_path = self.tcx.def_path_str(def_id);
if let Some(control_kind) =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Async spawn misses coroutine callees

High Severity

AsyncSpawn is classified, but operand_closure_instance still only matches Closure/FnDef, not Coroutine/CoroutineClosure. tokio::spawn of an async fn future therefore never records spawn_calls or a spawn ThreadControl edge to the task body, so alias-based join matching cannot recover the spawned task.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 96ea40a. Configure here.

Comment thread src/translate/callgraph.rs Resolved
}

let lockguard_id = LockGuardId::new(self.instance_id, destination.local);
let lockguard_id = Self::lockguard_id_for_dest(self.instance_id, destination);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drop call ignores projected guards

Medium Severity

Lock acquire and Drop terminators identify coroutine-state guards with lockguard_id_for_dest (field-sensitive), but the ::drop call path still builds LockGuardId::new without a field. Projected guards unlocked via an explicit drop call are missed, so the lock token is never returned.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 96ea40a. Configure here.

.and_then(|a| a.node.place())
.map(|p| format!("{:?}", p.ty(self.body, self.tcx).ty))
.unwrap_or_default();
log::warn!("[async] spawn: failed to resolve future from arg (ty={})", first_ty);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Join skips Pin handle locals

Medium Severity

AsyncJoin on Future::poll passes a Pin&lt;&amp;mut JoinHandle&gt; local into handle_join, which only looks up that local in spawn_handle_end. Refs are tracked in local_ref_source, but join never follows them (or Pin construction), so handle-identity join fails and falls back to spawn order.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 96ea40a. Configure here.

@kevindadi

Copy link
Copy Markdown
Owner Author

Progress: aliasing fix landed

Result: 4 locks → 2 real locks (AB–BA structure correct)

e725f3f + f7e5de1 fix the coroutine env binding in the PTA. The lock group output is now:

[lockgroup-detail] group0 ["{closure#0}::task1::__15(rx19fSome(1))", "{closure#0}::task2::__19(rx19fSome(0))"] = ParkingLotMutex
[lockgroup-detail] group1 ["{closure#0}::task1::__19(rx19fSome(0))", "{closure#0}::task2::__15(rx19fSome(1))"] = ParkingLotMutex
  • group0 = task1.b + task2.a → both are l2
  • group1 = task1.a + task2.b → both are l1

This is exactly the expected cross-task lock identity. Reduced net now has Mutex_0 + Mutex_1 only:

fixed petri net

Root cause of the fix

AggregateKind::Coroutine upvars were bound like a closure (_1.field_i ⊇ heap.field_i). An async fn coroutine instead reads upvars through the state pointer _1.0 (Pin<&mut State> → deref → (*_1.0).variant#N.k). The env phase now branches on tcx.is_coroutine and binds _1.0 → state heap (analysis.rs), so collapsed_receiver_points_to on {coroutine, _19, field} resolves to the right Arc<Mutex> allocation.

Genuine AB–BA deadlock now detected

State s294: task2 blocked at b.lock needing Mutex_1 (l1, held by task1), task1 suspended at sleep holding l1, main waiting on h1.await — no enabled transitions.

task2::{closure#0}_14 at src/main.rs:14  needs Mutex_1 (has 0, needs 1)
task1::{closure#0}_11 at src/main.rs:7    holds Mutex_1
main::{closure#0}_13  at src/main.rs:23   h1.await

Remaining (separate from aliasing): bug count 16 ≠ 1

The count is inflated because the model treats the coroutine suspend-return (_0 = Poll::Pending; return) like a near-terminal point and explores both Pending/Ready branches at the sleep().await, producing many reachable blocked configurations (tasks suspended holding locks while main waits). The one true AB–BA configuration is among them. Fixing the count to exactly 1 is a separate coroutine control-flow modeling concern (distinguish Poll::Pending suspend from Poll::Ready completion).

@kevindadi

Copy link
Copy Markdown
Owner Author

Status: aliasing problem fixed ✓

The original problem — four guards collapsing to the wrong four lock resources — is fixed by e725f3f (coroutine env binding in analysis.rs). Current branch async is 6 commits ahead of main.

What the fix changed

  • Coroutine env binding now branches on tcx.is_coroutine: _1.field_0 → state-heap (upvars read via Pin<&mut State> deref) instead of the closure-style _1.field_i ⊇ heap.field_i.
  • Result: Mutex_0 + Mutex_1 only, grouped as {task1.b, task2.a} = l2 and {task1.a, task2.b} = l1. The AB–BA deadlock (both tasks blocked at b.lock on each other's held lock) is reachable.

Remaining (documented, not part of the aliasing fix)

Bug count is 16, not 1. The deadlock detector flags every terminal state without main_end; the model treats a coroutine suspend (Poll::Pending return at sleep().await) as terminal, so "task suspended holding a lock + main waiting" states are counted alongside the one true AB–BA configuration. Fixing this requires coroutine resume modeling (suspend point → can be re-polled and continue), a separate coroutine control-flow concern. Recorded in docs/async-modeling.md.

Branch commits (vs main)

0867ddb Add async-deadlock benchmark implementation
a3ef386 Enhance async support in configuration and call graph analysis
d4c9da3 Refactor async tasks in deadlock benchmark
61ac08e Refactor LockGuardId and enhance BlockingCollector logic
2b1ab3c Refactor ConstraintBuilder for improved clarity and functionality
96ea40a Add async deadlock petri net visualization
e725f3f Bind coroutine state pointer in PTA env phase
f7e5de1 Add fixed async deadlock petri net visualization
294f48e Update async modeling doc: aliasing fixed, suspend-return remains

@kevindadi

Copy link
Copy Markdown
Owner Author

Final: bug count = 1 ✓ (genuine AB–BA deadlock)

6824e0e + d2d0747 model coroutine suspend/resume and dedupe the async join. The bench now reports exactly one deadlock:

Result   : BUG FOUND   (mode deadlock)
Bug count: 1   states=311, edges=754, reachable=311

The single incident is the genuine AB–BA: both tasks blocked at b.lock on each other's held Mutex, main waiting at h1.await:

task1::{closure#0}_14 at src/main.rs:8 (b.lock)
task2::{closure#0}_14 at src/main.rs:14 (b.lock)
main::{closure#0}_16 at src/main.rs:23 (h1.await)
needs Mutex_1 and Mutex_0  (both held, 0 tokens each)

What got fixed (3 issues driving the count from 16 → 1)

  1. Coroutine suspend-return (_0 = Poll::Pending; return) was treated as completion, spuriously finishing a task while it still held its lock. handle_return now resumes a suspend to its continuation instead of the function end.
  2. Coroutine state dispatch: bb0's discriminant switch explored resume states unconditionally, letting main reach an .await poll without its spawned task running. Now only the entry state (discriminant 0) is wired from bb0.
  3. Double join: .await lowers to both an into_future wrapper and a poll; both were wired as AsyncJoin, consuming the spawned task's end token twice and blocking main at the second join. Only the poll call is now the join.

final petri net

Regression check

Sync benchmarks (conflict-inter, lock-closure, inter, intra, static-ref, condvar-closure) are unchanged — all fixes are coroutine/async-scoped (tcx.is_coroutine guards in terminator.rs, join type-check in callgraph.rs).

Branch async is now 11 commits ahead of main (6 prior + 5 this round).

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

There are 5 total unresolved issues (including 3 from previous reviews).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit d2d0747. Configure here.

}
}
false
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fragile Pending suspend detection

Medium Severity

block_sets_poll_pending decides whether a coroutine return is a suspend by checking whether {:?} of the _0 assignment contains the substring Pending. Rustc often lowers Poll::Pending as an Aggregate/Adt with a numeric VariantIdx, so that Debug string may never include Pending, and suspends keep being treated as real completions (lock leak / wrong terminals).

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d2d0747. Configure here.

self.handle_fallthrough(bb_idx, &cont, name, "suspend");
}
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing suspend continuation dead-ends

Medium Severity

When a coroutine return is classified as Poll::Pending but find_suspend_continuation returns None, handle_return exits without adding any outgoing arc. The suspend block becomes a sink; tokens stuck there look like deadlocks even though the task should resume or complete.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d2d0747. Configure here.

@kevindadi
kevindadi merged commit 1046fe1 into main Aug 26, 2026
5 checks passed
@kevindadi
kevindadi deleted the async branch August 26, 2026 06:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant